package com.bungarus.group.config;

import com.bungarus.group.auth.SessionToken;
import com.bungarus.ratelimit.LimiterTokenParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * Configuration for initializing a authentication token parser bean
 * Created by tang on 2019/10/31.
 */
@Configuration
public class AuthTokenParserConfig {

    @Value("${token.tint}")
    String key;

    @Bean
    public LimiterTokenParser limiterTokenParser() {
        return new LimiterTokenParserImpl();
    }

    private class LimiterTokenParserImpl implements LimiterTokenParser {
        @Override
        public String parse(String token) {
            String result = "";
            Map<String, Long> IDsFromToken = SessionToken.parseIdentities(token, key);
            if (IDsFromToken.size() > 0) {
                result = String.valueOf(IDsFromToken.get(SessionToken.TENANT_ID)) + ":" + String.valueOf(IDsFromToken.get(SessionToken.USER_ID));
            }
            return result;
        }
    }
}
